package callHandler

import (
	"github.com/micro/go-micro/v2/broker"
	"gomicro/studentMicro/webServer/service"
	"gomicro/studentMicro/webServer/mainHandler"
	"fmt"
	"encoding/json"
	"log"
	"gomicro/studentMicro/model"
)

func init(){
	var req model.Student
	_, sErr := mainHandler.PubSub.Subscribe("go.micro.student.message", func(event broker.Event) error {
		
		if event.Message().Header["Method"] == "insert"{
			fmt.Println("消息体:", string(event.Message().Body))

			if jErr := json.Unmarshal(event.Message().Body, &req); jErr != nil {
				return jErr
			}
			fmt.Println(" 接收到信息：", req)

			var reqm map[string]string

			sss := service.StudentSriImp{}
			reqm = sss.InesrtSri(&req)
			msgBody, mErr := json.Marshal(reqm)
			if mErr != nil {
				log.Fatal(mErr.Error())
			}
			msg := &broker.Message{
				Header: map[string]string{
					"name": req.Name,
				},
				Body: msgBody,
			}
		
			err := mainHandler.PubSub.Publish("go.micro.member.message", msg)
			if err != nil {
				log.Fatal(" 消息发布失败：%s\n", err.Error())
			} else {
				log.Print("消息发布成功")
			}
			return nil
		}
		return nil
	})

	if sErr != nil {
		log.Printf("sub error: %v\n", sErr)
	}

}	